/****同步课程***/
//记录本地已有的课程id
var currCourseids;
var courseidArr;
//记录所有课程数据，以便存储到本地
var courseList;
var courseCount = 1;
//公共类
var localStorageManagers = require("script/localStorageManagers.js");
var downloadUtils = require('scripts/Core/DownLoadUtil.js');
var mobileFrame = require('scripts/Core/MobileFrame.js');
//mui初始化
mui.init({
	swipeBack: true //启用右滑关闭功能
});
mui('.mui-scroll-wrapper').scroll({
					indicators: false //是否显示滚动条
				});
//加载plusReady
if (window.plus) {
	plusReady();
} else {
	document.addEventListener("plusready", plusReady, false);
}
//
function plusReady() {
	currCourseids = '';
	courseList = new Array();
	courseidArr=new Array();
	loadCourse();
	//查看课程
	mui('#coursesdiv').on('tap', '.mui-course', showResView);
	//删除课程
	mui('#coursesdiv').on('longtap', '.mui-course', deleteStudycourse);
	//打开添加课程
	mui('header').on('tap', '#addselfcourse', openAddSelfcourse);
};
//加载课程
function loadCourse() {
	document.getElementById('coursesdiv').innerHTML = ' ';
	//loadCourseLocal(); //加载本地课程
	if (hasNet()){
		document.getElementById('nettip').style.display='none';
		loadCourseAjax(); //ajax加载课程
	}else{
		document.getElementById('nettip').style.display='block';
	}
}
//是否有网
function hasNet() {
	var isNet = mobileFrame.IsNetWorkCanUse();
	return isNet;
}
//本地加载
function loadCourseLocal() {
	courseList = localStorageManagers.getSynccourseSession();
	if (courseList != null) {
		var courseulEle = document.getElementById("courseul");
		mui.each(courseList, function(index, course) {
			currCourseids += course.courseId + ",";
			courseidArr.push(course.courseId);
			buildCourseDiv(course);
			courseCount++;
		});
	}
}
//远程加载课程列表数据
function loadCourseAjax() {
	if (courseList == null) courseList = new Array();
	//if(currCourseids.length>0)currCourseids=currCourseids.substring(0,currCourseids.length-1);
	var userid = localStorageManagers.getUseridSession();
	console.log(serverAjax + 'mobile/course/getSelfCourseList.do');
	var w = plus.nativeUI.showWaiting();
	mui.ajax(serverAjax + 'mobile/course/getSelfCourseList.do', {
		data: {
			userid: userid,
			currCourseids: currCourseids
		},
		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		timeout: 10000, //超时时间设置为10秒；
		success: function(data) {
			w.close();
			if (data.length == 0) {
				ifHasnewCourse = false;
				return;
			}
			for (var i = 0; i < data.length; i++) {
				var course = data[i];
				courseList.push(course);
				buildCourseDiv(course);
				currCourseids += course.courseId + ",";
				courseidArr.push(course.courseId);
				courseCount++;
			}
			if(currCourseids.length>0)currCourseids=currCourseids.substring(0,currCourseids.length-1);
			localStorageManagers.setSynccourseSession(courseList);
		},
		error: function(xhr, type, errorThrown) {
			w.close();
			ajaxErrorTip();
			//异常处理；
			console.log(xhr);
		}
	});
}
//打开课程资源页面
function showResView() {
	var courseid = this.getAttribute('courseid');
	mui.openWindow({
		url: 'selfcoursecatalog.html',
		id: 'selfcenter/selfstudycourse/selfcoursecatalog',
		extras: {
			'courseid': courseid,
			type:1
		}
	});
}
//删除课程
function deleteStudycourse(){
	var ts=this;
	var courseid = ts.getAttribute('courseid');
	mui.confirm('您要删除该课程吗？', '', null, function(e) {
		if (e.index == 0) {
			var userid = localStorageManagers.getUseridSession();
			var url=serverAjax+'mobile/course/deleteSelfCourse.do';
			var w = plus.nativeUI.showWaiting();
			mui.ajax(url,{
				data:{courseid:courseid,userid:userid},
				type:'post',
				dataType:'json',
				timeout:10000,
				success:function(data){
					w.close();
					if(data==null)return;
					if(data.state==0){
					  for(var i=0;i<courseidArr.length;i++){
					  	if(courseidArr[i]==courseid)courseidArr.splice(i, 1); 
					  }
					  ts.parentNode.removeChild(ts);	
					  mui.toast('删除课程成功');
					}
				},
				error:function(e1,e2,e3){
				   w.close();
			       ajaxErrorTip();
			       //异常处理；
			       console.log(xhr);
				}
			});
		}
	});
}
function getBackColor() {
	var bColor = 'b1';
	var yu = courseCount % 4;
	switch (yu) {
		case 1:
			bColor = 'b1';
			break;
		case 2:
			bColor = 'b2';
			break;
		case 3:
			bColor = 'b3';
			break;
		case 0:
			bColor = 'b4';
			break;
	}
	return bColor;
}
//构建课程div
function buildCourseDiv(course) {
	var courseDivEle = document.getElementById('courseid_' + course.courseId);
	if (courseDivEle != null) courseDivEle.parentNode.removeChild(courseDivEle);
	var bColor = getBackColor();
	var viewcount=1;
	if(course.viewCount>0)viewcount=course.viewCount;
	var divstr = '<div class="mui-course" id="courseid_' + course.courseId + '" courseid="' + course.courseId + '">' + '<div class="course-top ' + bColor + '">' + '<div class="c1">' + '<span class="cmsg"><img src="../../images/tip.png" />&nbsp;教师上传了计机械设计机械设计机</span> ' + '<span class="cname">' + course.title + '</span>  ' + '<span class="ctype">'+course.catName+'</span>' + ' </div>' + '<div class="c2">' + '	<span class="cuser"><img src="../../images/tou.png" />&nbsp;'+viewcount+'学生学习</span>' + '</div>' + '</div>' + '<div class="course-foot">' + '<span class="title">学习课程</span><span class="navigate-right"></span>' + '</div>' + '</div>';

	document.getElementById('coursesdiv').innerHTML = document.getElementById('coursesdiv').innerHTML + divstr;
}
//下载资源
function downloadResource(src) {
	// plus.downloader.enumerate(function(tasks){
	//  	alert("当前下载任务数量:"+tasks.length);
	//  });
	//调用父页面方法

	downloadUtils.downloadFileWidthLocalCache(src, {
		beforeDownload: function() {
			//记录该下载资源信息：资源本身信息，课程、课题信息
		},
		successDownload: function(relativePath) {
			console.log('下载成功:' + relativePath);
			mui.plusReady(function() {
				var sd_path = plus.io.convertLocalFileSystemURL(relativePath);
				console.log('存储路径：' + sd_path);
			});
		},
		errorDownload: function(msg) {}
	});
	//var curTasks=DownloadUtil.getCurrentDownloadTasks();
	//var conCurTasks=DownloadUtil.getConcurrentDownloadTask();
	// mui.toast("当前下载任务数量:"+conCurTasks.CurrentTaskCount);
};
//打开添加课程页面
function openAddSelfcourse() {
	if(!hasNet())return;
	mui.openWindow({
		url:'addselfcourse.html',
		id:'selfcenter/selfstudycourse/addselfcourse',
		extras:{currCourseids:courseidArr.join(',')}
	});
}